package com.netted.studentbook.http;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.netted.studentbook.application.BaseApplication;

import java.util.Map;

/**
 * Created by lu on 2018/6/22.
 */

public class HttpRequest {


    public void get(String url,String tag,final Callback callback) {
        Log.d("get request url",url);
        if (tag == null){
            tag = "GET";
        }

        BaseApplication.getRequestQueue().cancelAll(tag);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                callback.onSuccess(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                callback.onError(error);
            }
        });

        stringRequest.setTag(tag);

        BaseApplication.getRequestQueue().add(stringRequest);
    }

    public void post(String url, final Map<String,String> params, String tag, final Callback callback) {
        Log.d("post request url",url);
        if (tag == null){
            tag = "POST";
        }
        BaseApplication.getRequestQueue().cancelAll(tag);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                callback.onSuccess(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                callback.onError(error);
            }
        })

        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return params;
            }
        };

        stringRequest.setTag(tag);
        stringRequest.setRetryPolicy(
                new DefaultRetryPolicy(
                        600000,//默认超时时间，应设置一个稍微大点儿的，例如本处的500000
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES,//默认最大尝试次数
                        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
                )
        );
        BaseApplication.getRequestQueue().add(stringRequest);
    }

    public interface Callback {
        void onSuccess(String response);

        void onError(VolleyError error);
    }
}
